package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vos.ApUserLoginSuccessVO;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.MD5Utils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Objects;

@Service
public class ApUserServiceImpl extends ServiceImpl<UserMapper, ApUser> implements ApUserService {

    /**
     * 用户登录
     *
     * @param apUser
     * @return {@link ApUserLoginSuccessVO}
     */
    @Override
    public ApUserLoginSuccessVO login(ApUser apUser) {
        //todo 1.用户登录
        if (StringUtils.isNoneBlank(apUser.getPhone(),apUser.getPassword())){
            // todo 1.1 根据手机号判断用户是否存在
            LambdaQueryWrapper<ApUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(ApUser::getPhone,apUser.getPhone());
            ApUser apUserByPhone = baseMapper.selectOne(lambdaQueryWrapper);
            if (Objects.isNull(apUserByPhone)) {
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //todo 1.2 判断密码是否合法 --- 原始密码+盐 --- MD5加密 --- 和数据库加密后的密码进行比较
            String password = apUser.getPassword() + apUserByPhone.getSalt();
            String psw = DigestUtils.md5DigestAsHex(password.getBytes());
            if (!psw.equals(apUserByPhone.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            ApUserLoginSuccessVO apUserLoginSuccessVO = new ApUserLoginSuccessVO();
            apUserByPhone.setSalt(null);
            apUserByPhone.setPassword(null);
            String token = AppJwtUtil.generateToken(Long.valueOf(apUserByPhone.getId()));
            apUserLoginSuccessVO.setToken(token);
            apUserLoginSuccessVO.setUser(apUserByPhone);
            return apUserLoginSuccessVO;
        }
        //todo 2.游客登录 --- 没有手机号和密码
        String token = AppJwtUtil.generateToken(0L);
        ApUserLoginSuccessVO apUserLoginSuccessVO = new ApUserLoginSuccessVO();
        apUserLoginSuccessVO.setToken(token);
        apUserLoginSuccessVO.setUser(null);
        return apUserLoginSuccessVO;
    }
}
